package com.zhongxi.guoyuan.view.beautifulStore;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectDetailData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectDetailResult;
import com.zhongxi.guoyuan.entity.user.center.MyInfo;
import com.zhongxi.guoyuan.fragment.beautifulStore.BeautifulStoreCommentFragment;
import com.zhongxi.guoyuan.fragment.beautifulStore.BeautifulStoreDetailFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zhongxi.guoyuan.R.id.tvSure;

public class ProjectDetailActivity extends BaseActivity implements View.OnClickListener, MyScrollView.OnScrollListener {

    private Button btComment;
    private Button btDetail;
    private BeautifulStoreDetailFragment detailFragment;
    private BeautifulStoreCommentFragment commentFragment;
    private Fragment[] fragments;
    private int index = 0;
    private int currentIndex = 0;
    private Button[] tabs;
    private LinearLayout linearLayout;
    private LinearLayout linearScrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private int scrollHeight;
    private MyScrollView scrollView;
    private TextView tvOrder;
    private String id;
    private TextView tvName;
    private TextView tvOrign;
    private TextView tvView;
    private TextView tvTime;
    private TextView tvCash;
    private TextView tvRedBean;
    private Banner banner;
    private ProjectDetailData basicData;
    private UMShareAPI mShareAPI;
    private SHARE_MEDIA platform;
    private View popupWindow_view;
    private PopupWindow popupWindow;
    private Map<String, String> map = new HashMap<String, String>();
    private String type;
    private ProjectDetailResult result;
    private LinearLayout btShare;
    private LinearLayout btCollection;
    private RelativeLayout title;
    private ProgressDialog mDialog;
    private ImageView iv_unread_dot;
    private RelativeLayout rl_content;
    private ImageView iv_service;
    private int count;
    public static final int requestFulsh = 500;
    public static final int requestFulshConver = 600;
    public static final int REQUEST_CODE = 200;
    public static final int RESULT_CODE = 400;
    private static final int PROGECTCODE = 300;
    private PopupWindow pw;
    private ImageView ivCollection;
    private TextView text_collect;


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            scrollHeight = linearLayout.getBottom();//获取searchLayout的顶部位置
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_project_detail);
        title = (RelativeLayout) findViewById(R.id.title);

        mShareAPI = UMShareAPI.get(this);

        id = getIntent().getStringExtra("id");  //服务id  既是项目
        initTitle();
        tvTitle.setText("美容项目详情");

        btDetail = (Button) findViewById(R.id.btDetail);
        btComment = (Button) findViewById(R.id.btComment);
        btDetail.setSelected(true);

        tvName = (TextView) findViewById(R.id.tvName);
        tvOrign = (TextView) findViewById(R.id.tvOrign);
        tvView = (TextView) findViewById(R.id.tvView);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvRedBean = (TextView) findViewById(R.id.tvRedBean);
        btShare = (LinearLayout) findViewById(R.id.btShare);
        banner = (Banner) findViewById(R.id.ivTopImage);
        btCollection = (LinearLayout) findViewById(R.id.btCollection);
        ivCollection = (ImageView) findViewById(R.id.ivCollection);

        rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        iv_service = (ImageView) findViewById(R.id.iv_service);
        iv_unread_dot = (ImageView) findViewById(R.id.iv_dot);
        text_collect = (TextView) findViewById(R.id.text_collect);

        RelativeLayout frame = (RelativeLayout) findViewById(R.id.frame);
        ImageUtils.setHeight(this, Constants.detailRate, frame);
        //上拉悬停
        scrollStop();

        InitViewPager();

        tvOrder = (TextView) findViewById(R.id.tvOrder);

    }

    /**
     *
     */
    @Override
    protected void initData() {
        super.initData();
        type = "detail";
        getServer(Url.SERVICE_DETAILS, null, "&sid=" + id, false, null, "get");

    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("detail".equals(type)) {
                result = gson.fromJson(response, ProjectDetailResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                //初始化基本数据
                initProjectData(result);
            } else if ("collection".equals(type)) {
                BaseResponse res = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(res.getSafeobj());
                ivCollection.setImageResource(R.mipmap.iv_hascollect);
                showShortToast("收藏成功！");
                text_collect.setText("已收藏");
                text_collect.setTextColor(getResources().getColor(R.color.red));
            } else if ("myinfo".equals(type)) {
                MyInfo myInfo = gson.fromJson(response, MyInfo.class);
                if (null != myInfo.getSafeobj() && !"".equals(myInfo.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(myInfo.getSafeobj());
                }
                if (null != myInfo.getUserInfo() && !"".equals(myInfo.getUserInfo())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(myInfo.getUserInfo().getIsshareholders())).commit();
                }
                if (String.valueOf(myInfo.getSharesnum()) != null) {
                    MyApplication.getInstance().sharedPrefrences.edit().putInt("point", myInfo.getSharesnum()).commit();
                }

                if ((null != String.valueOf(myInfo.getInnernum()) && myInfo.getInnernum() > 0)
                        || (null != myInfo.getRedbeannum() && DataUtil.moreThanOtherNoEqual(myInfo.getRedbeannum(), "0"))) {
                    showGetBackSilverDialog(myInfo.getInnernum(), myInfo.getRedbeannum());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 活动返现
     *
     * @param backSilver
     * @param redbeannum
     */
    private void showGetBackSilverDialog(int backSilver, String redbeannum) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_back_silver, null);
//        View view = View.inflate(this, R.layout.dialog_back_silver, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_back_cancle);
        TextView tv_HD_number = (TextView) view.findViewById(R.id.tv_HD_number);
        TextView tv_MD_number = (TextView) view.findViewById(R.id.tv_MD_number);

        if (backSilver > 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText(redbeannum + "  红豆");
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver > 0 && !DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.GONE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver <= 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.GONE);
            tv_HD_number.setText(redbeannum + "  红豆");
        } else {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText("0  红豆");
            tv_MD_number.setText("0  美豆");
        }
        TextView tvSure = (TextView) view.findViewById(R.id.tv_back_silver_sure);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if (null != res.getSafeobj() && !"".equals(res.getSafeobj()))
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            if (res.getCode() == 1000) {
                showShortToast("该项目已下架！");
                finish();
            }
            if (1682 == res.getCode()) {
                ivCollection.setImageResource(R.mipmap.iv_hascollect);
                showShortToast("该项目已收藏");
                text_collect.setText("已收藏");
                text_collect.setTextColor(getResources().getColor(R.color.red));
            } else if (1001 == res.getCode()) {
                showShortToast("用户未登录，请先登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化项目详情数据
     *
     * @param result
     */
    private void initProjectData(ProjectDetailResult result) {
        try {
            if (null != result.getBasic() && !"".equals(result.getBasic())) {
                basicData = result.getBasic();
                if (null != basicData.getName() && !"".equals(basicData.getName())) {
                    tvName.setText(basicData.getName());
                } else {
                    tvName.setText("");
                }
                if (null != basicData.getInnerprice() && !"".equals(basicData.getInnerprice())) {
                    tvCash.setText(basicData.getInnerprice() + " 美豆");
                } else {
                    tvCash.setText("0 美豆");
                }

                if (null != basicData.getMarketprice() && !"".equals(basicData.getMarketprice())) {
                    tvOrign.setText("市场价: " + basicData.getMarketprice() + " 元");
                    tvOrign.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                } else {
                    tvOrign.setText("");
                }
                if (null != basicData.getViewnum() && !"".equals(basicData.getViewnum())) {
                    tvView.setText(basicData.getViewnum() + "");
                } else {
                    tvView.setText("");
                }
                if (null != basicData.getRedbeanprice() && !"".equals(basicData.getRedbeanprice())) {
                    tvRedBean.setText("+" + basicData.getRedbeanprice() + " 红豆");
                } else {
                    tvRedBean.setText("+0 红豆");
                }
                if (null != basicData.getServicetime() && !"".equals(basicData.getServicetime())) {
                    tvTime.setText(basicData.getServicetime() + " 分钟");
                } else {
                    tvTime.setText("");
                }

                if (null != basicData.getImages() && !"".equals(basicData.getImages())) {
                    banner.isAutoPlay(true);
                    banner.setDelayTime(3000);
                    banner.setIndicatorGravity(BannerConfig.CENTER);
                    List<String> images = new ArrayList<>();
                    for (int i = 0; i < basicData.getImages().size(); i++) {
                        images.add(Url.IMG_URL + basicData.getImages().get(i));
                    }
                    banner.setImages(images).setImageLoader(new GlideImageLoader()).start();
                }
            }
            //初始化详情数据
            detailFragment.initProjectData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
        }
    }

    /**
     * 上滑悬停
     */
    private void scrollStop() {
        scrollView = (MyScrollView) findViewById(R.id.scrollView);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        linearScrollBody = (LinearLayout) findViewById(R.id.linearScrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
        scrollView.setOnScrollListener(this);
    }

    private void InitViewPager() {
        tabs = new Button[2];
        tabs[0] = (Button) findViewById(R.id.btDetail);
        tabs[1] = (Button) findViewById(R.id.btComment);
        tabs[0].setSelected(true);
        detailFragment = new BeautifulStoreDetailFragment(id);
        commentFragment = new BeautifulStoreCommentFragment(id);
        fragments = new Fragment[]{detailFragment, commentFragment};
        getSupportFragmentManager().beginTransaction()
                .add(R.id.relaContainer, detailFragment).commit();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        rl_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.checkApkExist(ProjectDetailActivity.this,"com.tencent.mobileqq")){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin="+Constants.QQ_NUM+"&version=1")));
                }else {
                    showShortToast("未安装QQ");
                }
    }
});
        //收藏
        btCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收藏
                getCollection();
            }
        });
        //分享
        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
            }
        });
        btDetail.setOnClickListener(this);
        btComment.setOnClickListener(this);
        tvOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (null == MyApplication.getInstance().getUserId() || "".equals(MyApplication.getInstance().getUserId())) {
                        Intent intent = new Intent(context, LoginActivity.class);
                        startActivityForResult(intent, PROGECTCODE);
                    } else {
                        Intent intent = new Intent(context, SubscribeActivity.class);
                        intent.putExtra("id", id);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void getCollection() {
        if (!MyTextUtils.isFastDoubleClick()) {
            map.clear();
            map.put("ftype", "1");
            map.put("refid", id);
            type = "collection";
            getServer(Url.ADD_FAVORITE, map, "", false, null, "post");
        }
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(btShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }

                UMWeb mUMWeb=new UMWeb(Url.IMG_URL + "/Home/pars/offline_get_url?id=" + id);
                mUMWeb.setTitle("美容何必付现金！豆豆就能做美容=免费美容！");
                mUMWeb.setDescription("在自己手机里免费下载一个属于自己的美容院，从此以后“免费”美容！");
                mUMWeb.setThumb(new UMImage(ProjectDetailActivity.this, R.mipmap.logo));

                new ShareAction(ProjectDetailActivity.this).setPlatform(platform)
                        .setCallback(umShareListener)
                        .withMedia(mUMWeb)
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btDetail:
                btDetail.setSelected(true);
                btComment.setSelected(false);
                btComment.setSelected(false);
                index = 0;
//                if (linearScrollBody.getParent() != linearBegin) {
//                    linearStop.removeView(linearScrollBody);
//                    linearBegin.addView(linearScrollBody);
//                }
                break;
            case R.id.btComment:
                btDetail.setSelected(false);
                btComment.setSelected(true);
                index = 1;
//                if (linearScrollBody.getParent() != linearBegin) {
//                    linearStop.removeView(linearScrollBody);
//                    linearBegin.addView(linearScrollBody);
//                }
                break;
        }
        if (index != currentIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (fragments[currentIndex].isAdded()) {
                trx.hide(fragments[currentIndex]);
            }
            if (!fragments[index].isAdded()) {
                trx.add(R.id.relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
            tabs[index].setSelected(true);
            tabs[currentIndex].setSelected(false);
            currentIndex = index;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= scrollHeight) {
            if (linearScrollBody.getParent() != linearStop) {
                linearBegin.removeView(linearScrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(linearScrollBody.getMeasuredWidth(), linearScrollBody.getMeasuredHeight()));

                linearStop.addView(linearScrollBody);
            }
        } else {
            if (linearScrollBody.getParent() != linearBegin) {
                linearStop.removeView(linearScrollBody);
                linearBegin.addView(linearScrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestFulsh) {
            pw.dismiss();
        } else if (requestCode == requestFulshConver) {
            pw.dismiss();
        } else if (requestCode == PROGECTCODE) {
            if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId())) {
                getMyInfo();
            }
        } else if (requestCode == REQUEST_CODE && resultCode == SubscribeActivity.RESULT_CODE) {
            setResult(RESULT_CODE);
            finish();
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void getMyInfo() {
        type = "myinfo";
        getServer(Url.MYINFO, null, "", false, null, "get");
    }
}
